package com.abe.config;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.RandomAccessFile;

public class ReadWriteFile {
	public static BufferedReader bufread;
	// 指定文件路径和名称
	private static String path;
	private static File filename;
	public static String readStr = "";

	@SuppressWarnings("static-access")
	public ReadWriteFile(String path) {
		this.path = path;
		this.filename = new File(path, "Command.txt");
	}

	/**
	 * 创建文本文件.
	 * 
	 * @throws IOException
	 * 
	 */
	public static void creatTxtFile() throws IOException {
		if (filename.exists() && filename.isFile()) {
			filename.delete();
		}
		filename.createNewFile();
	}

	public static void OpenTxtFile() {
		filename = new File(path, "Command.txt");
	}

	/**
	 * 读取文本文件.
	 * 
	 */
	public static void readTxtFile() {
		String read;
		FileReader fileread;
		try {
			fileread = new FileReader(filename);
			bufread = new BufferedReader(fileread);
			try {
				while ((read = bufread.readLine()) != null) {
					readStr = readStr + read + "\r\n";
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 写文件.
	 * 
	 */
	public static void writeTxtFile(String newStr) throws IOException {
		// 先读取原有文件内容，然后进行写入操作
		String filein = newStr+ "\r\n";
		RandomAccessFile mm = null;
		try {
			mm = new RandomAccessFile(filename, "rw");
			mm.writeBytes(filein);
		} catch (IOException e1) {
			e1.printStackTrace();
		} finally {
			if (mm != null) {
				try {
					mm.close();
				} catch (IOException e2) {
					e2.printStackTrace();
				}
			}
		}
	}
}
